<?php
// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2007 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
//公共函数
function toDate($time, $format = 'Y-m-d H:i:s') {
    if (empty ( $time )) {
        return '';
    }
    $format = str_replace ( '#', ':', $format );
    return date ($format, $time );
}

function get_client_ip() {
    if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
        $ip = getenv ( "HTTP_CLIENT_IP" );
    else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
        $ip = getenv ( "HTTP_X_FORWARDED_FOR" );
    else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
        $ip = getenv ( "REMOTE_ADDR" );
    else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
        $ip = $_SERVER ['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return ($ip);
}
// 缓存文件
function cmssavecache($name = '', $fields = '') {
    $Model = D ( $name );
    $list = $Model->select ();
    $data = array ();
    foreach ( $list as $key => $val ) {
        if (empty ( $fields )) {
            $data [$val [$Model->getPk ()]] = $val;
        } else {
            // 获取需要的字段
            if (is_string ( $fields )) {
                $fields = explode ( ',', $fields );
            }
            if (count ( $fields ) == 1) {
                $data [$val [$Model->getPk ()]] = $val [$fields [0]];
            } else {
                foreach ( $fields as $field ) {
                    $data [$val [$Model->getPk ()]] [] = $val [$field];
                }
            }
        }
    }
    $savefile = cmsgetcache ( $name );
    // 所有参数统一为大写
    $content = "<?php\nreturn " . var_export ( array_change_key_case ( $data, CASE_UPPER ), true ) . ";\n?>";
    file_put_contents ( $savefile, $content );
}

function cmsgetcache($name = '') {
    return DATA_PATH . '~' . strtolower ( $name ) . '.php';
}
function getStatus($status, $imageShow = true) {
    switch ($status) {
        case 0 :
            $showText = '禁用';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
            break;
        case 2 :
            $showText = '待审';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/prected.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
            break;
        case - 1 :
            $showText = '删除';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
            break;
        case 1 :
        default :
            $showText = '正常';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';

    }
    return ($imageShow === true) ?  $showImg  : $showText;

}
function getDefaultStyle($style) {
    if (empty ( $style )) {
        return 'blue';
    } else {
        return $style;
    }

}
function IP($ip = '', $file = 'UTFWry.dat') {
    $_ip = array ();
    if (isset ( $_ip [$ip] )) {
        return $_ip [$ip];
    } else {
        import ( "ORG.Net.IpLocation" );
        $iplocation = new IpLocation ( $file );
        $location = $iplocation->getlocation ( $ip );
        $_ip [$ip] = $location ['country'] . $location ['area'];
    }
    return $_ip [$ip];
}

function getNodeName($id) {
    if (Session::is_set ( 'nodeNameList' )) {
        $name = Session::get ( 'nodeNameList' );
        return $name [$id];
    }
    $Group = D ( "Node" );
    $list = $Group->getField ( 'id,name' );
    $name = $list [$id];
    Session::set ( 'nodeNameList', $list );
    return $name;
}

function get_pawn($pawn) {
    if ($pawn == 0)
        return "<span style='color:green'>没有</span>";
    else
        return "<span style='color:red'>有</span>";
}
function get_patent($patent) {
    if ($patent == 0)
        return "<span style='color:green'>没有</span>";
    else
        return "<span style='color:red'>有</span>";
}


function getNodeGroupName($id) {
    if (empty ( $id )) {
        return '未分组';
    }
    if (isset ( $_SESSION ['nodeGroupList'] )) {
        return $_SESSION ['nodeGroupList'] [$id];
    }
    $Group = D ( "Group" );
    $list = $Group->getField ( 'id,title' );
    $_SESSION ['nodeGroupList'] = $list;
    $name = $list [$id];
    return $name;
}

function getCardStatus($status) {
    switch ($status) {
        case 0 :
            $show = '未启用';
            break;
        case 1 :
            $show = '已启用';
            break;
        case 2 :
            $show = '使用中';
            break;
        case 3 :
            $show = '已禁用';
            break;
        case 4 :
            $show = '已作废';
            break;
    }
    return $show;

}

function showStatus($status, $id) {
    switch ($status) {
        case 0 :
            $info = '<a href="javascript:resume(' . $id . ')">恢复</a>';
            break;
        case 2 :
            $info = '<a href="javascript:pass(' . $id . ')">批准</a>';
            break;
        case 1 :
            $info = '<a href="javascript:forbid(' . $id . ')">禁用</a>';
            break;
        case - 1 :
            $info = '<a href="javascript:recycle(' . $id . ')">还原</a>';
            break;
    }
    return $info;
}
//处理okhome 业务审核状态
function showYesNo($status) {
    switch ($status) {
        case 0 :
            $info = "<font style='color:red'>否</font>";
            break;
        default:
            $info = "是";
    }
    return $info;
}

/**
 +----------------------------------------------------------
 * 获取登录验证码 默认为4位数字
 +----------------------------------------------------------
 * @param string $fmode 文件名
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function build_verify($length = 4, $mode = 1) {
    return rand_string ( $length, $mode );
}


function getGroupName($id) {
    if ($id == 0) {
        return '无上级组';
    }
    if ($list = F ( 'groupName' )) {
        return $list [$id];
    }
    $dao = D ( "Role" );
    $list = $dao->findAll ( array ('field' => 'id,name' ) );
    foreach ( $list as $vo ) {
        $nameList [$vo ['id']] = $vo ['name'];
    }
    $name = $nameList [$id];
    F ( 'groupName', $nameList );
    return $name;
}
function sort_by($array, $keyname = null, $sortby = 'asc') {
    $myarray = $inarray = array ();
    # First store the keyvalues in a seperate array
    foreach ( $array as $i => $befree ) {
        $myarray [$i] = $array [$i] [$keyname];
    }
    # Sort the new array by
    switch ($sortby) {
        case 'asc' :
        # Sort an array and maintain index association...
            asort ( $myarray );
            break;
        case 'desc' :
        case 'arsort' :
        # Sort an array in reverse order and maintain index association
            arsort ( $myarray );
            break;
        case 'natcasesor' :
        # Sort an array using a case insensitive "natural order" algorithm
            natcasesort ( $myarray );
            break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key => $befree ) {
        $inarray [] = $array [$key];
    }
    return $inarray;
}

/**
 +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码
 * 默认长度6位 字母和数字混合 支持中文
 +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function rand_string($len = 6, $type = '', $addChars = '') {
    $str = '';
    switch ($type) {
        case 0 :
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        case 1 :
            $chars = str_repeat ( '0123456789', 3 );
            break;
        case 2 :
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
            break;
        case 3 :
            $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        default :
        // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
            break;
    }
    if ($len > 10) { //位数过长重复字符串一定次数
        $chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 );
    }
    if ($type != 4) {
        $chars = str_shuffle ( $chars );
        $str = substr ( $chars, 0, $len );
    } else {
        // 中文随机字
        for($i = 0; $i < $len; $i ++) {
            $str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 );
        }
    }
    return $str;
}
function pwdHash($password, $type = 'md5') {
    return hash ( $type, $password );
}
/**
 * 得到配置变量的一维数组,根据状态如果是借出，未归还，未付等状态，自动显红返回。
 * 注意：系统配置变量中消费记录，借还记录的“未归还”，“借出”，“未付”如果变了，这里也要修改。
 *@show_color 默认为1,显示对应的特别状态颜色；如果为0，则不显示
 */
function getConfigVal($key,$title,$show_color = 1) {
    $result = C($title);
    $returnStr = "";
    if(empty($key)) {
        if($result[0]=="等待发货"||$result[0]=="借出" ||$result[0]=="未付" ) {
            if($show_color)
                $returnStr = '<font color="red">'.$result[0].'</font>';
            else
                $returnStr = $result[0];
        }
        else {
            $returnStr = $result[0];
        }
    }
    else {//可能遇到0时会有问题TODO
        if( ($result[$key]=="等待发货"||$result[$key]=="借出" ||$result[$key]=="未付" 
            || $result[$key]=="运费不匹配" || $result[$key]=="货款不匹配" || $result[$key]=="总金额不匹配") && $show_color
            ) {
            $returnStr = '<font color="red">'.$result[$key].'</font>';
        }
        
        else if( $result[$key]=="对账成功" && $show_color )
            $returnStr = '<font color="green">'.$result[$key].'</font>';
        else {

            $returnStr = $result[$key];
        }
    }
    return $returnStr;
}

function getSex($id) {
    switch ($id) {
        case 1:
            return '男';
            break;
        case 2:
            return '女';
            break;
        default:
            return '---';
    }
}

/**
 *通过模型的ID，默认获取名称，也可获取其他字段
 * @param <type> $id 模型主键
 * @param <type> $model 模型名称
 * @param <type> $field 获取的字段，默认为name
 * @return <type>
 */
function getModelName($id,$model,$field='name') {
    $id = intval($id);
    return M($model)->where('id='.$id)->getField($field);
}

//返回会员的帐号及姓名的链接
function getMemberFullNameLink($id){
    $result = M('Member')->where('id = '.intval($id))->field('account,name')->find();
    $fullName = $result['account'].'('.$result['name'].')';
    return '<a href="__APP__/Member/edit/id/'.$id.'">'.$fullName.'</a>';
}


function getAllMember(){
    $data = M('Member')->where('status = 1')->field('id,account,name')->findAll();
    $result = array();
    foreach($data as $key=>$value){
        $result[ $value['id'] ] = $value['account'].'('.$value['name'].')';
    }
    return $result;
    //ajaxReturn($data,'',1);
}

/**
 *返回产品的名称（公寓或房型）
 * @param <type> $type 0房型,1公寓
 */
function getPName($pid,$type){
  $model = $type==0 ? 'House':'Hotel';
  return getModelName($pid, $model);
}

function cutstr($string, $length = 100, $dot = ' ...') {
	$charset = 'utf-8';
	$string = preg_replace ('/\s+/m', ' ', $string);
	if (strlen($string) <= $length) {
		return $string;
	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	if (strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while ($n < strlen($string)) {
			$t = ord($string[$n]);
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n++;
				$noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n++;
			}
			if ($noc >= $length) {
				break;
			}
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
	} else {
		for ($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

//special for jquery ui autocomplete remote datasource
function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = "\"".addslashes($key)."\"";

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "\"".addslashes($value)."\"";
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

  /**
     *判断是否该房间已经有人预订或入住
     * @param <type> $startTime 入住时间或离开时间
   * @param <type> $TransId 入住单的ID或预订单ID，适用于更新时，防止与自身比较
     */
    function isOverlap($room_id,$startTime,$endTime,$TransId){
        $ordermap['room_id'] = $room_id;
        if(!empty( $TransId )){//排除自身
            $ordermap['id'] = array('neq',$TransId);
        }
        $ordermap['status'] = array('between','3,4');//只关注预订定金或口头确定的状态
        $result = M('Order')->where($ordermap)->findAll();
        $isOverlap = false;
        foreach ($result as $value) {
            $start_time = $value['start_time'];
            $end_time = $value['end_time'];
            if( ($startTime >= $start_time) && ($startTime <= $end_time) ){//交叉关系
                $isOverlap = true;
                break;
            }
            if( ($endTime >= $start_time) && ($endTime <= $end_time) ){//交叉关系
                $isOverlap = true;
                break;
            }
            if( ($startTime < $start_time) && ($endTime > $end_time) ){//包含关系
                $isOverlap = true;
                break;
            }
        }
        if($isOverlap){
            return true;
        }else {//入住单情况
            $map['room_id'] = $room_id;
            if(!empty( $TransId )) {//排除自身
                $map['id'] = array('neq',$TransId);
            }
            $result = M('Checkin')->where($map)->findAll();
            foreach ($result  as $v2) {
                $start_time = $v2['start_time'];
                $end_time = $v2['end_time'];
               $end_realtime = $v2['end_realtime'];
               if($end_realtime == 0){//无实际离开时间
                     if( ($startTime >= $start_time) && ($startTime <= $end_time) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($endTime >= $start_time) && ($endTime <= $end_time) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($startTime < $start_time) && ($endTime > $end_time) ) {//包含关系
                       $isOverlap = true;
                       break;
                   }

               }
               else{//有实际离开时间
                        if( ($startTime >= $start_time) && ($startTime <= $end_realtime) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($endTime >= $start_time) && ($endTime <= $end_realtime) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($startTime < $start_time) && ($endTime > $end_realtime) ) {//包含关系
                       $isOverlap = true;
                       break;
                   }
               }
               
            }
            return $isOverlap;
        }
       
    }
   


    function getCheckInfo($checkin_id="",$type=""){
        return $member_name = getModelName($checkin_id, 'Checkin',$type);
    }
    //获取当前公寓下属的房型列表链接
    function hotel_children_link($obj_id=''){
        $count_house = M('House')->where('hotel_id ='.$obj_id)->count();
         return '<a href="__APP__/House/index/hotel_id/'.$obj_id.'">下属房型('.$count_house.')</a>';
    }

    /**
     * 返回该model的编辑链接，类似于 member/edit/id/$id
     * @param <type> $id
     * @param <type> $model
     * @param <type> $field 超链接显示的锚文本字段
     * @return <type>
     */
    function model_edit_link($id,$model,$field='name') {
    $id = intval($id);
    $title = M($model)->where('id='.$id)->getField($field);
    return '<a href ="__APP__/'.$model.'/edit/id/'.$id.'">'.$title.'</a>';
    }

    function getConfigDataJson($cfg_name,$id_name,$value_name){
        $configArray = C($cfg_name);
        $newJson = "[";
        $arrLength = count($configArray);
        for($i=0;$i< $arrLength;$i++){
            if($i == $arrLength-1){//最后一个
                $newJson .="{".$id_name.":\"".$i."\",".$value_name.":\"".$configArray[$i]."\"}]";
            }else{
                $newJson  .="{".$id_name.":\"".$i."\",".$value_name.":\"".$configArray[$i]."\"},";
            }
        }
        echo $newJson;
    }

    /**
     * 返回所有公寓的房型，房间树,
     * return json data
     */
    function getHotelTreeJson(){
        $newJson = "[";
        $hotels = M('Hotel')->where('status = 1')->order('sort asc')->findAll();
        $length1 = count($hotels);
        foreach($hotels as $key => $value){
            $newJson .= "{\"id\":\"ht".$value['id']."\",\"text\":\"".$value['name']."\"";
            //$newJson .= "{\"id\":\"ht".$value['id']."\",\"text\":\"".$value['name']."\",\"state\":\"closed\"";
            $houses = M('House')->where('hotel_id ='.$value['id'].' and status = 1')->order('sort asc')->findAll();
            if($houses){//有房型
                $newJson .= ",\"state\":\"closed\",
                    \"children\":[";
                $length2 = count($houses);
                foreach ($houses as $key2 => $value2) {
                    $newJson .= "{\"id\":\"hu".$value2['id']."\",\"text\":\"".$value2['name']."\"";
                    $rooms = M('Room')->where('house_id ='.$value2['id'].' and status = 1')->order('sort asc')->findAll();
                    if($rooms) {//取房间
                        $newJson .= ",
                    \"children\":[";
                        $length3 = count($rooms);
                        foreach ($rooms as $key3 => $value3) {
                            if($key3 == ($length3 -1 ) ){//最后一个节点
                                $newJson .= "{\"id\":\"rm".$value3['id']."\",\"text\":\"".$value3['room_no']."\"}]}";
                            }else{
                                 $newJson .= "{\"id\":\"rm".$value3['id']."\",\"text\":\"".$value3['room_no']."\"},";
                            }
                            
                        }
                    }else{//没有房间
                        $newJson .= "}";
                    }
                    if ($key2 < ($length2 - 1 )) {
                       $newJson .= ",";
                    } else {//最后一个节点
                       $newJson .= "]}";//TODO
                    }
                }
            } else {//没有房型
                $newJson .= "}";
            }
            if ($key < ($length1 - 1 )) {
               $newJson .= ",";
            } else {//最后一个节点
               $newJson .= "]";//整个json树结束
            }
        }

        echo $newJson;
    }

    function jsonFilter($sourceStr) {
        $sourceStr = str_replace("\\", "\\\\", $sourceStr);
        $sourceStr = str_replace("\b", "\\\b", $sourceStr);
        $sourceStr = str_replace("\t", "\\\t", $sourceStr);
        $sourceStr = str_replace("\n", "\\\n", $sourceStr);
        $sourceStr = str_replace("\n", "\\\n", $sourceStr);
        $sourceStr = str_replace("\f", "\\\f", $sourceStr);
        $sourceStr = str_replace("\r", "\\\r", $sourceStr);
        $sourceStr = str_replace("\r\n", "\\r\\n",$sourceStr);//替换换行
        $sourceStr = str_replace(chr(13),' ',$sourceStr);//回车
	$sourceStr = str_replace(chr(10),' ',$sourceStr);//换行
        return str_replace("\"", "\\\"", $sourceStr);
    }

    //返回该入住单的消费记录及借还记录的详情链接
    function other_detail_link($checkin_id){
        return '<a href="__URL__/other_detail/id/'.$checkin_id.'">消费借还记录</a>';
    }

    /**
 * 一次给多个用户发送邮件,
 */
function multiSendMail($subject='',$message='',$from='',$to='') {
	$from = preg_replace('/\v*/', '', $from);
	if (empty($from) || empty($to)) {
		return false;
	}
	$to = explode(',',preg_replace('/\v*/', '', $to.','.C('SERVEEMAIL')));
	foreach($to as $value) {
		if (!empty($value)) {
			sendMail($subject,$message,$from,$value);
		}
	}
}

// 参数设置 string $subject, string $message, 'name <name@server.suffix>' $from, 'name1 <name1@server1.suffix>,name2 <name2@server2.suffix>....' $to
function sendMail($subject='',$message='',$from='',$to='') {
	if (empty($subject) || empty($to)) {
		throw new Exception('参数错误');
	}
	$mail = array(
			'charset' => "UTF-8",
			'adminemail' => "mikegao@dayanwo.com",
			'sendmail_silent' => 1,
			'maildelimiter' => 1,
			'mailusername' => 1,
			'mailsubject' => $subject,
			'mailmessage' => $message,
			'from' => $from,
			'mailto' => $to,
			'server' => "smtp.exmail.qq.com",
			'port' => 25,
			'mailsend' => 2,
			'auth' => 1,
			'auth_username' => 'mikegao@dayanwo.com',
			'auth_password' => 'gc654123',
	);

	if($mail['sendmail_silent']) {
		error_reporting(0);
	}

	$email_from = $mail['from'];
	$email_to = $mail['mailto'];
	$charset = isset($mail['charset']) ? $mail['charset'] : 'UTF-8';
	$maildelimiter = $mail['maildelimiter'] == 1 ? "\r\n" : ($mail['maildelimiter'] == 2 ? "\r" : "\n");
	$mailusername = isset($mail['mailusername']) ? $mail['mailusername'] : 1;

	$email_subject = '=?'.$charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', $mail['mailsubject']))).'?=';
	$email_message = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $mail['mailmessage'])))))));

	$email_from = $email_from == '' ? '=?'.$charset.'?B?'.base64_encode('管理员')."?= <".$mail['adminemail'].">" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.$charset.'?B?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);

	foreach(explode(',', $email_to) as $touser) {
		$tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($mailusername ? '=?'.$charset.'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;
	}
	$email_to = implode(',', $tousers);

	$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Mailman{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=$charset{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";

	$mail['port'] = $mail['port'] ? $mail['port'] : 25;

	if($mail['mailsend'] == 1 && function_exists('mail')) {

		@mail($email_to, $email_subject, $email_message, $headers);

	} elseif($mail['mailsend'] == 2) {

		if(!$fp = fsockopen($mail['server'], $mail['port'], $errno, $errstr, 30)) {
			throw new Exception('SMTP ', "($mail[server]:$mail[port]) CONNECT - Unable to connect to the SMTP server", 0);
		}
		stream_set_blocking($fp, true);

		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != '220') {
			throw new Exception('SMTP '."$mail[server]:$mail[port] CONNECT - $lastmessage");
		}

		fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." Mailman\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
			throw new Exception('SMTP '."($mail[server]:$mail[port]) HELO/EHLO - $lastmessage");
		}

		while(1) {
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
				break;
			}
			$lastmessage = fgets($fp, 512);
		}

		if($mail['auth']) {
			fputs($fp, "AUTH LOGIN\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) AUTH LOGIN - $lastmessage");
			}

			fputs($fp, base64_encode($mail['auth_username'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) USERNAME - $lastmessage");
			}

			fputs($fp, base64_encode($mail['auth_password'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 235) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) PASSWORD - $lastmessage");
			}

			$email_from = $mail['from'];
		}

		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 250) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) MAIL FROM - $lastmessage");
			}
		}

		$email_tos = array();
		foreach(explode(',', $email_to) as $touser) {
			$touser = trim($touser);
			if($touser) {
				fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
				$lastmessage = fgets($fp, 512);
				if(substr($lastmessage, 0, 3) != 250) {
					fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
					$lastmessage = fgets($fp, 512);
					throw new Exception('SMTP '."($mail[server]:$mail[port]) RCPT TO - $lastmessage");
				}
			}
		}

		fputs($fp, "DATA\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 354) {
			throw new Exception('SMTP '."($mail[server]:$mail[port]) DATA - $lastmessage");
		}
                //将gmdate改为date，以使用当前时区
		$headers .= 'Message-ID: <'.date('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";
                fputs($fp, "Date: ".date('r')."\r\n");
		fputs($fp, "To: ".$email_to."\r\n");
		fputs($fp, "Subject: ".$email_subject."\r\n");
		fputs($fp, $headers."\r\n");
		fputs($fp, "\r\n\r\n");
		fputs($fp, "$email_message\r\n.\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			throw new Exception('SMTP '."($mail[server]:$mail[port]) END - $lastmessage");
		}

		fputs($fp, "QUIT\r\n");

	} elseif($mail['mailsend'] == 3) {

		ini_set('SMTP', $mail['server']);
		ini_set('smtp_port', $mail['port']);
		ini_set('sendmail_from', $email_from);

		@mail($email_to, $email_subject, $email_message, $headers);

	}
}

//绘制县列表
function makeCountry($selected) {
	$lists = M("Country")->select();
	$select = "<select name='coun_code' id='coun_code'>";
	if(0 == $selected) {
		$select .= "<option value='-1'>请选择城市</option>";
	}
        $result = M("Country")->field("city_code")->where("coun_code={$selected}")->find();
	$lists = M("Country")->where("city_code={$result['city_code']}")->select();
	foreach($lists as $value) {
		if($selected == $value["coun_code"]) {
			$select .= "<option value='{$value['coun_code']}' selected>{$value['coun_name']}</option>";
		}else {
			$select .= "<option value='{$value['coun_code']}'>{$value['coun_name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}

//绘制省列表
function makeProvince($selected) {
	$lists = M("Province")->select();
	$select = "<select name='prov_code' id='prov_code' onchange='modifyCity(this);'>";
	if(0 == $selected) {
		$select .= "<option value='-1'>请选择省</option>";
	}
	foreach($lists as $value) {
		if($selected == $value["prov_code"]) {
			$select .= "<option value='{$value['prov_code']}' selected>{$value['prov_name']}</option>";
		}else {
			$select .= "<option value='{$value['prov_code']}'>{$value['prov_name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}
//绘制城市列表
function makeCity($selected) {
	if(0 == $selected) {
		return "<select id='city_code' name='city_code' onchange='modifyCountry(this);'><option value='-1'>请选择规格</option></select>";
	}
	$select = "<select id='city_code' name='option_id' onchange='modifyOption(this);'>";
	$result = M("City")->field("prov_code")->where("city_code={$selected}")->find();
	$lists = M("City")->where("prov_code={$result['prov_code']}")->select();
	foreach($lists as $value) {
		if($selected == $value["city_code"]) {
			$select .= "<option value='{$value[city_code]}' selected>{$value['city_name']}</option>";
		}else {
			$select .= "<option value='{$value[city_code]}'>{$value['city_name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}


//绘制规格列表
function makeOption($selected) {
	if(0 == $selected) {
		$select = "<select id='city_code' name='option_id' onchange='modifyOption(this);'><option value='-1'>请选择规格</option>";
	}else{
    $select = "<select name='option_id' onchange'modifyOption(this);'>";    
    
    }

    $lists = M('Option')->where('status = 1') -> findAll();
	foreach($lists as $value) {
		if($selected == $value["id"]) {
			$select .= "<option value='{$value['id']}' selected>{$value['name']}</option>";
		}else {
			$select .= "<option value='{$value['id']}'>{$value['name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}

/**
 *通过产品编号获取对应的单位
 * //TODO 做成通用性
 * @param <type> $pid
 */
function getProductUnit($pid){
    $unit_id = getModelName($pid, 'Product', 'unit_id');
    return getModelName($unit_id, 'Unit');
}

function getStock($product_id,$warehouse_id=1){
    $map = array(
        'product_id' => $product_id,
        'warehouse_id' => $warehouse_id,
        );
    $number = M('Stock')->where($map)->getField('number');
    return empty($number)?0 : $number;
}

//获得默认仓库的产品库存及明细 和链接
 function getDStock($pid){
        $sid = M('Stock')->where('product_id = '.$pid.' and warehouse_id = 1')->getField('id'); 
    return '<a href="__APP__/Stock/detail/id/'.$sid.'">'.getStock($pid,1).'</a>';
  }

  /**update 小交易的total，同时更新整个大单子的total
  @type 交易类型 如Enter，Sale 首字母大写
  @return void
  **/
  function updateTotalPrice($type,$trans_detail_id,$number,$price){
    $type = ucfirst(strtolower($type));//将第一个字母强制变成大写
    $detail = M($type.'_detail');
    $small_type = strtolower($type);
    $rs = $detail->where('id = '.$trans_detail_id)->setField('total',$number*$price);
    if($rs){//更新成功
        $parent_id = getModelName($trans_detail_id,$small_type.'_detail',$small_type.'_id');
        $total = $detail->where($small_type.'_id = '.$parent_id)->sum('total');
        M($type)->where('id = '.$parent_id)->setField('total',$total);
    }
  }

  /**update 更新整个大单子的sum_number 总数量
  @type 交易类型 如Enter，Sale 首字母大写
  @return void
  **/
  function updateSumNumber($type,$trans_detail_id,$number){
    $type = ucfirst(strtolower($type));//将第一个字母强制变成大写
    $detail = M($type.'_detail');
    $small_type = strtolower($type);
    $parent_id = getModelName($trans_detail_id,$small_type.'_detail',$small_type.'_id');
    //总数量之和
    $total = $detail->where($small_type.'_id = '.$parent_id)->sum('number');
    M($type)->where('id = '.$parent_id)->setField('sum_number',$total);
  }


  //返回Model id,name.volist使用时，$key ,$vo
  function getModelIdName($model,$sort=""){
    $model = ucfirst(strtolower($model));//首字母大写
    if(!empty($sort))
        return M($model)->where('status=1')->order($sort)->getField('id,name');
    else
        return M($model)->where('status=1')->getField('id,name');
  }

  

/*获取表的字段值，相对getModelIdName更灵活些，volist 使用时，二维数组 vo.id,vo.name...vo.field
**@field 多个字段使用,隔开
**/
function getModelField($model,$field ='id,name',$map="status = 1",$sort=""){
    $model = ucfirst(strtolower($model));//首字母大写
    if(!empty($sort))
        return M($model)->where($map)->order($sort)->field($field)->findAll();
    else
        return M($model)->where($map)->field($field)->findAll();
  }

/**返回对应model select html list
** @mod 类型，如user,supplier,unit
**@void 当前model vo.id,if eq,then selected
**@ class 默认当前的select 宽度 span2
**/
function modList($mod,$void = -1,$class='span2',$name='',$sort=""){
    if(empty($mod)){
        echo 'None Type';
        return false;
    }
        
    $lowcase_mod = strtolower($mod);
    $fupcase_mod = ucfirst($lowcase_mod);

    $lists = getModelIdName($fupcase_mod,$sort);
    if(empty($name))
        $name = empty($name)? $lowcase_mod.'_id' : $name; //默认变量名mod_id

    $selectStr = ' <select name="'.$name.'" class="'.$class.'">';
    $selectStr.='<option value="">--请选择--</option>';
    foreach ($lists as $key => $value) {
        $selectStr.='<option value="'.$key.'"';
        if($lowcase_mod == 'user' && ($_SESSION[C('USER_AUTH_KEY')] == $key ) && $void != '')
            $selectStr.='selected ';
        else if($void == $key && $void != '' )
            $selectStr.='selected ';

        $selectStr.='>'.$value.'</option>';
    }
    $selectStr .= '</select>';
    return $selectStr;
}
/***
** 返回配置变量的select html list
**@mod 配置的变量名，如orderStatus
**@name 返回的select name .默认为status
**@void 当前model vo.id,if eq,then selected
**@class 默认当前的select 宽度 span2
**/
function configList($mod,$void = -1,$name='status', $class='span2' ){
    $selectStr = '<select name="'.$name.'" class="'.$class.'">';
    $selectStr.='<option value="">--请选择--</option>';
    foreach ($mod as $key => $value) {
        $selectStr.='<option value="'.$key.'"';
        if($void == $key && $void != '' )
            $selectStr.='selected ';

        $selectStr.='>'.$value.'</option>';
    }
    $selectStr .= '</select>';
    return $selectStr;
}

    /**
    /**根据货品名称，生成货品编码及相关数组并返回
    /**@goods 货品标题
    /**@return_code 1为返回货品编码，0 返回数组
    **/
    function build_code($goods,$return_code=1) {
      //$goods = "博士伦水灵焕彩隐形眼镜年抛一片装-摩卡棕-8.00";

      $product = array();
      if (S('products')) {
          $products = S('products');
      }else{
          $products = M('Common_product')->where('status = 1')->findAll();
          S('products',$products);
      }
      $ps = array();//temp products
        foreach ($products as $k=> $v) {
          $is_brand = strpos($goods,$v['name']);
          if($is_brand !== false){ //不存在，则返回是False,注意==
              $ps[$k] = $v;
          }
      }
       //取最长标题的做为匹配的产品     
       $len = 0;
       foreach($ps as $ke => $va ){
           if(strlen($va['name']) > $len ){
               $len = strlen( $va['name'] );
               $product = $va;
           }
       }

      if(empty($product))
        return null;

      $brand = array();
      if (S('brands')) {
          $brands = S('brands');
      }else{
          $brands = M('Brand')->where('status = 1')->findAll();
          S('brands',$brands);
      }
      
      foreach ($brands as $value) {
          $is_brand = strpos($goods,$value['name']);
          //默认取第一个匹配的品牌
          if($is_brand !== false){ //不存在，则返回是False,注意==
              $brand = $value;
              break;
          }
            
      }

      if(empty($brand))
        return null;

      $option_values = array();
      $option_code = '';  //规格编码
      if (S('option_value')) {
          $option_value = S('option_value');
      }else{
         $option_value = M('Option_value')->where('status = 1')->findAll();
          S('option_value',$option_value);
      }
      foreach ($option_value as $k => $vo) {
          $is_brand = strpos($goods,$vo['name']);
          if($is_brand !== false){ //不存在，则返回是False,注意==
              $option_values[$k] = $vo;
              $option_code .= $vo['mano'];
          }
      }

      if(empty($option_values))
        return null;

      $all_code = $product['mano'].$brand['mano'].$option_code;
      $all_array = array(
            'product' => $product,
            'brand' => $brand,
            'option' => $option_values,
            'all_code' => $all_code
        ); 
      if($return_code)
        return $all_code;
      else
        return $all_array;
    }

    //获取货品的详细参数，包括：产品，品牌及规格
    function getGoodsDetail($goods_id='')
    {
        $pnumber = M('Product')->where('id = '.$goods_id)->getField('pnumber');
        $pmano = '';  //产品编码
        $brand_mano = ''; //品牌编码
        $option_values = array(); //规格数组

        $length = strlen($pnumber)/4;   //有几位元素
        for ($i=0; $i < $length; $i++) { 
          if ($i == 0)
            $pmano = substr($pnumber, 0,4);
          elseif ($i == 1) {
            $brand_mano = substr($pnumber, 4,4);
          }
          else{
            $option_values[$i] = substr($pnumber, 4*$i,4);
          }
        }
        //分解对应的数组及名称，规格，规格值
        $brand =  M('Brand')->getByMano($brand_mano);
        $common_product = M('Common_product')->getByMano($pmano);
        if(empty($brand) || empty( $common_product ))
            return null;
        $data = array(
             'brand_mano' => $brand_mano,
             'brand_name' => $brand['name'],
             'common_mano' => $pmano,
             'common_name' => $common_product['name'] , 
        );

        $option = array(); //规格详细参数
        foreach($option_values as $key => $value){
            $rs = M('Option_value')->where('mano = "'.$value.'"')->find();
            $option[$key] = array(
                 'name' => $rs['name'],
                 'mano' => $value,
                 'option_id' => $rs['option_id'],
                 'option' => getModelName($rs['option_id'],'Option'),
            );
        }
        $data['option'] = $option;
        return $data;
    }
//笛卡尔乘积    
function Descartes() {  
      $t = func_get_args();  
        if(func_num_args() == 1) return call_user_func_array( __FUNCTION__, $t[0] );  
          $a = array_shift($t);  
            if(! is_array($a)) $a = array($a);  
              $a = array_chunk($a, 1);  
                do {  
                      $r = array();  
                        $b = array_shift($t);  
                          if(! is_array($b)) $b = array($b);  
                            foreach($a as $p)  
                              foreach(array_chunk($b, 1) as $q)  
                                $r[] = array_merge($p, $q);  
                                  $a = $r;  
                                    }while($t);  
                                      return $r;  
}   

//get option_value detail,return array includes value_id,value_name,option_id,option_name
function getOptionValueDetail($mano){
    $value = M('Option_value')->getByMano($mano);
    $data = array(
        'option_id' => $value['option_id'],
        'value_id' => $value['id'],
        'option_name' =>getModelName( $value['option_id'] ,'Option'),
        'value_name' => $value['name']
    ); 
   return $data;
}

    //返回 三维数组的kye like array_search()
    function array_search_re($needle, $haystack, $a=0, $nodes_temp=array()){
       global $nodes_found;
       $a++;
       foreach ($haystack as $key1=>$value1) {
               $nodes_temp[$a] = $key1;
                   if (is_array($value1)){    
                            array_search_re($needle, $value1, $a, $nodes_temp);
                                 }
                                     else if ($value1 === $needle){
                                               $nodes_found[] = $nodes_temp;
                                                   }
       } 
       return $nodes_found;
   }

   //get 3rd source product map,default is jingwei
   //返回以第三方商品编码为key,我方产品common_id为值的一维数组
   function getPmap($order_source_id = 1 ){
        if(S('pmap'))
             $pmap = S('pmap');
        else{
            $pmap = M('Product_map')->findAll();
            S('pmap',$pmap);
        }
     $jw_map = array();
     foreach($pmap as $k => $v){
       if($v['order_source_id'] == $order_source_id ) // get jingwei products
           $jw_map [$v['out_number']] = $v['my_number']; 
     }
    if(is_array($jw_map))
        return $jw_map ;
    else
        return null;
   }

   //通过货品编号，返回京卫第三方产品的编码，默认京卫体系：第三方编码对应我方产品编码，而非货品
   function getOut_number($product_id,$order_source_id = 1){
        $jw_map = getPmap($order_source_id);
        $common_id = getModelName($product_id,'Product','common_id');
        
        $k = array_search($common_id, $jw_map);
       
        if( $k  !== false )
            return $k;
        else
            return 0;

   }

 //get my_number for goods_id 获取货品的编号，通常应用于货品第三方映射
  function getMyGoodsId_real($order_source_id,$out_number){
    $t = getPmap($order_source_id);
    $helpword = $t[$out_number]; //通常第三方商品映射通过人工编码映射
    if(S('goods'))
        $goods = S('goods');
    else
        $goods = M('Product')->where('status = 1')->getField('id,helpword');
    foreach($goods as $k=>$v){
       if( $helpword == $v['helpword'] )
          return $k;
       else
           continue ;
    }
    return 0;
}

   //TODO 暂时不用，使用货品名称 代替
   //根据货品编号生成对应的销售标题，如隐形眼镜，则为 颜色 + 度数 ，度数 为标准格式；若是护理液，则直接显示名称
   function makeSale_title($goods_id){
        $product = M('Common_product')->getById( getModelName($goods_id,'Product','common_id' ));
        $options = getGoodsDetail( $goods_id );
        $option_str = array();
        foreach ($options['option'] as $op) {
            if($op['option'] == '光度'  )
                $option_str['gd'] = $op['name']; 
            if($op['option'] == '颜色'  )
                $option_str['color'] = $op['name']; 
        }
        if(count($option_str) >0 )
            return $product['name'].' '.$option_str['color'].' '.$option_str['gd'];
        else
            return $product['name'];
   }

  //查找第三方系统中传来的产品 是否是我方产品,默认查找第三方平台为1的产品.成功则返回对应我方产品ID(common_id)
  //否则返回0 
   function getMyProductId($out_number,$order_source_id = 1){
       $jw_map = getPmap($order_source_id);
       return empty($jw_map [ $out_number]) ? 0 : $jw_map[$out_number ] ;
   }

   function getMyGoodsIdJw($out_number,$sale_title){
    
        //先处理淘宝上转来的订单,格式为 名称+(颜色分类:欧美蓝;度数:0)
        $k = strrpos($sale_title ,"(");
        if($k > 0 ){
            $options = substr($sale_title, $k);
            if(strpos($options, '(颜色分类') !== false ||
               strpos($options, '度数:') !== false ){
                $options = str_replace('(', '', $options);
                $options = str_replace(')', '', $options);
                $options = str_replace(':', '：', $options);

                return getMyGoodsId($out_number,$options,1);
            }
        }
        
            

       $product_id = getMyProductId($out_number );
       if($product_id == 0)
           return 0;

       
       $k = strrpos($sale_title ," ");
       //度数
       $last_option = substr($sale_title ,$k);
       $sale_second = substr($sale_title ,0,$k);
       if ($last_option )
            $last_option = trim($last_option );
      //颜色
      $second_option = substr($sale_second, strrpos($sale_second," ") );
      if($second_option )
          $second_option = trim($second_option );
       if($last_option === false && $second_option === false )
           return M('Product')->where('common_id ='.$product_id  )->getField('id');

       $option_value = S('option_value');
       $option_name_mano = array(); 
       foreach( $option_value as $key => $value){
            $option_name_mano[$value['name']] = $value['mano'];
       }
       $color_mano = $option_name_mano[$second_option ];
       if($last_option == "平光")
           $last_option = "+0.00";
       $dushu_mano = $option_name_mano[$last_option ];
       //若出现两个同类型的规格值,如京东传来的会有-1.00 -7.25,则返回最后一个规格值
       $color_option_type = M('Option_value')->where('mano = "'.$color_mano.'"')->getField('option_id');
       $dushu_option_type = M('Option_value')->where('mano = "'.$dushu_mano.'"')->getField('option_id');
       if($color_option_type == $dushu_option_type  ){
             $color_mano = false;
        }
       $goods = M('Product')->where('common_id ='.$product_id)->findAll();
       //只有一个货品
       if(count($goods) == 1 )
           return $goods['0'] ['id'];
       foreach ($goods as $k => $v) {
        //去掉产品 common_mano,brand_mano,仅剩下纯粹的规格值
        $option_mano = substr( $v['pnumber'],8);
        if($option_mano == false ){
             return $v['id'];      //只有产品及品牌编码的,则表示产品 下仅有当前一个货品.
        }
        $length = strlen($option_mano  )/4;   //有几位规格
        $option_values = array();
        for ($i=0; $i < $length; $i++) {
            $option_values[$i] = substr($option_mano, 4*$i,4);
            //如果是彩片，传值颜色却为空，则直接返回0
            if(empty($color_mano)){
                 $option_id =  M('Option_value')->where('mano ="'.$option_values[$i].'"')->getField('option_id');
                 if($option_id == 2) //颜色规格
                    return 0;
            }
                
        }
        

        if($color_mano){
            $c_key = array_search( $color_mano ,$option_values );
            $d_key = array_search($dushu_mano, $option_values  );
            if( $c_key !== false && $d_key !== false  ) 
             return $v['id'];
        }else{
        
            $d_key = array_search($dushu_mano, $option_values  );
            //适用于php4.2+
            if($d_key !== false )
               return $v['id'];
        }
     }
        return 0;
   }

   /*暂适用于淘宝导入 的产品
   *获取我方货品ID
   *@out_number 第三方编码
   *@options 第三方传过来的商品属性
   */
   function getMyGoodsId($out_number,$options,$order_source_id =1){
       $product_id = getMyProductId($out_number,$order_source_id );
       if($product_id == 0)
           return 0;

       //如果规格为空,则直接返回产品 对应 的唯一货品,取第一个
       if(empty($options))
           return M('Product')->where('common_id ='.$product_id  )->getField('id');

       //$options = "颜色分类：菠萝棕;度数：475";
       /* 以下方式仅适用于php5.3+
       $s = strstr($options,'度数：');
       $c = strstr($options,';',true);
       
       $color = str_replace('颜色分类：','',$c);
       $dushu = str_replace('度数：','',$s);  或以下方式
       */
       $clear_sub = str_replace('颜色分类：','',$options);
       $clear_sub = str_replace('度数：','',$clear_sub);

       $sub = explode(';', $clear_sub);
       $option_value = S('option_value');
       $option_name_mano = array(); 
       foreach( $option_value as $key => $value){
            $option_name_mano[$value['name']] = $value['mano'];
       }

       $dushu = "+0.00";
       if(count($sub) >1 ){ //有度数和颜色
           if($sub[1] ==0 )
               $dushu = "+0.00";
           else
               $dushu = '-'.sprintf("%1.2f",$sub[1]*0.01 );
       }else{
            if($sub[0] ==0 )
               $dushu = "+0.00";
           else
               $dushu = '-'.sprintf("%1.2f",$sub[0]*0.01 );
       }

       $error_color = 0; //是否是正确的颜色规格
       if(count($sub) >1 ){ //有度数及颜色
            //如果有空格的，则分开处理。类似：半年抛 黑色
            if(strpos($sub[0], " ") !== false ){
                $p = explode(" ", $sub[0]);
                  $color_mano = NULL;
                  $o = S('option_value');
                  foreach ($o as $key_o => $value_o) {
                    if($value_o['option_id'] == 2 ) //color option
                      foreach ($p as $kp => $vp) {
                        if($value_o['name'] == $vp ){
                          $color_mano = $value_o['mano'];
                          break;
                        }
                      }
                  }
            }else
                $color_mano = $option_name_mano[$sub[0]];
            if($color_mano === NULL )
                $error_color = 1; //说明颜色规格有误
       }else
            $color_mano = NULL;
       $dushu_mano = $option_name_mano[$dushu];
       $goods = M('Product')->where('common_id ='.$product_id)->findAll();
       
       if(count($goods) == 1 )
           return $goods['0'] ['id'];
       foreach ($goods as $k => $v) {
        //去掉产品 common_mano,brand_mano
        $option_mano = substr( $v['pnumber'],8);
        if($option_mano == false ){
             return $v['id'];      //只有产品及品牌编码的,则表示产品 下仅有当前一个货品.
        }
        $length = strlen($option_mano  )/4;   //有几位规格
        $option_values = array();
        for ($i=0; $i < $length; $i++) { 
            $option_values[$i] = substr($option_mano, 4*$i,4);
        }
        if($color_mano){
            $c_key = array_search( $color_mano ,$option_values );
            $d_key = array_search($dushu_mano, $option_values  );
            if( $c_key !== false   && $d_key !== false   ) 
                return $v['id'];
        }else{
            $d_key = array_search($dushu_mano, $option_values  );
            if($d_key !== false && $error_color != 1 )  //如果是颜色编码错误，则返回0
               return $v['id'];
        }
           
       }
       return 0;
   }

   /*check if exist duplicate goods,only used for jingwei tmall
   *@order_no 订单编号
   *@out_number 第三方商品编码
   *@options 商品属性
   *@is_option 如果 是,则传入的是规格,否则传入产品销售 标题,适用于京卫系统
   **/
   function checkExistOrder_detailRecord($order_no,$out_number,$options,$is_option=1){
    //如果已经导入了订单的，则不再导入产品，返回已存在。避免原订单中删除的重又导入
        if($rs3 = M('Sale')->where('sale_no ="'.$order_no.'"')->field('id')->find() )
           return true;

       //$goods_id = getMyGoodsId($out_number,$options); //exchange to goods id
       $sale_detail = M('Sale_detail');

       $map = array(
          'out_number' => $out_number ,
          'sale_no' => $order_no,
       );
       if($is_option == 1 ){ //淘宝导入 的订单
           $map['options'] = $options;
        }else{
           $map['sale_title'] = $options;  
        }
      $rs = $sale_detail->where($map )->field('id')->find();
      if($rs)
          return true;
      else{
            if($is_option == 1 ){ //淘宝订单
                $where = array();
                $where['mall_no'] = $order_no;   //京卫已导入的订单，再在淘宝导入时不再导入
                $rs2 = M('Sale')->where($where )->field('id')->find();
                if($rs2)
                    return true;
            }

          return false;
      }
          
   }

   function getGoodsIdByHelpword($helpword='')
   {
     if( empty($helpword) )
        return 0;
       $goods_id = M('Product')->where('helpword = "'.trim($helpword).'"')->getField('id'); //exchange to goods id
       if($goods_id)
            return $goods_id;
        else
            return 0;
   }

   /***
   **检查是否存在订单详情-商品明细记录，如果存在记录，则返回true；否则 false
   ** @order_no 订单号
   ** @out_number 第三编码
   ** @is_helpword 传过来的第三方编码是否是人工编码；若是，默认为1表是。
   **/
    function checkExistOrder_detailRecord_tb($order_no,$out_number,$is_helpword = 1){
    //如果已经导入了订单的，则不再导入产品，返回已存在。避免原订单中删除的重又导入
        if($rs3 = M('Sale')->where('sale_no ="'.$order_no.'"')->field('id')->find() )
           return true;
       //如果是处理人工编码，则按人工编码返回对应的商品ID，否则直接返回第三方编码做为商品ID
       if($is_helpword)
            $goods_id = getGoodsIdByHelpword($out_number);
       else{ //传过来的纯粹是商品ID
            if(substr($out_number, 0,1) == 0 || strlen($out_number) >5 )
                return true; //如果位数大于5或开头是0，则返回true，不继续处理
           $goods_id = M('Product')->where('id = '.$out_number)->getField('id') ;
       
       }
        if(!$goods_id)
            return true; //如果不能对应系统产品，则返回true,不导入
       $sale_detail = M('Sale_detail');
       $map = array(
          'product_id' => $goods_id ,
          'sale_no' => $order_no,
       );
      $rs = $sale_detail->where($map )->field('id')->find();
      if($rs)
          return true;
      else
          return false;
      
          
   }
 
 //检查是否可以写入订单到订单表.满足sale_detail表有相应订单记录,sale表无订单记录,则可以插入,返回true;
   function shouldAddOrder($order_no){
      $sd = M('Sale_detail')->where('sale_no ="'.$order_no.'"')->field('id')->find();
      $sr = M('Sale')->where('sale_no ="'.$order_no.'" or mall_no = "'.$order_no.'"')->field('id')->find();
      if($sd && !$sr )
          return true;
      else
          return false;
   }

    //临时使用：是否有淘宝订单已经插入的，如果没有，则可以新增订单
   function shouldAddMallOrder($mall_no='')
   {
      $sr = M('Sale')->where('sale_no ="'.$mall_no.'"')->field('id')->find();
      if(!$sr )
          return true;
      else
          return false;
   }

   //get customer id if exist,or create a new customer and return customer id
   function getCustomerId($name,$alipay,$mobile = "",$phone=""){
    
        $data = array(
             'name' => $name,
             //'alipay' => $alipay
          );
        if(!empty($alipay))
            $data['alipay'] = $alipay;
        if(!empty($mobile))
            $data['mobile'] = $mobile;
        if(!empty($phone))
            $data['phone'] = $phone;

       $rs = M('Customer')->where($data)->getField('id');
       if($rs)
           return $rs;
       else{
          $data = array(
             'name' => $name,
             'man' => $name,
             'alipay' => empty($alipay) ? "" : $alipay ,
             'mobile' => empty($mobile) ? "" : $mobile,
             'phone' => empty($phone)? "" : $phone,
             'create_time' => time(),
          );
          $new_customer_id = M('Customer')->add($data); 
          if( $new_customer_id > 0 )
              return $new_customer_id;
          else
              return 0;
       }
   }
   
   //get shipping address id or create new shipping address ,and return id
   function getShippingAddressId($customer_id,$name,$address,$mobile,$phone){
       $shipping = M('Shipping_address');
       $condata = array(
           //'customer_id' => $customer_id , //不用判断客户ID，药房网之类customer_id存在重复
           'name' => $name,
           'address' => $address,
           //'mobile' => $mobile,
           //'phone' => $phone ,
       );
       if(!empty($mobile))
            $condata['mobile'] = $mobile;
        if(!empty($phone))
            $condata['phone'] = $phone;

       if($rs = $shipping ->where($condata )->getField('id') )
           return $rs;
        else{
            $condata ['customer_id'] = $customer_id;
            $condata ['create_time'] = time();
           if($sid = $shipping ->add( $condata )  )
               return $sid;
           else
               return 0;
        }
   }

   //统一订单状态,传入淘宝或京卫订单,返回系统中对应 的唯一订单状态
   function getOrderStatus($order_status){
       $orderStatus = 0 ;
       switch ($order_status ){
         case "等待买家付款":{
             $orderStatus = 1;
             break;
         }    
         case "买家已付款，等待卖家发货":{
             $orderStatus = 2;
             break;
         }    
         case "卖家已发货，等待买家确认":{
             $orderStatus = 3;
             break;
         }    
         case "交易成功":{
             $orderStatus = 4;
             break;
         }    
         case "交易关闭":{
             $orderStatus = 5;
             break;
         }
         case "卖家部分发货":{
             $orderStatus = 2; //下载的订单一般未进入系统，是我们要发货的。还是转换成待发货
             break;
         }     
         case "异常订单":{
             $orderStatus = -1;
             break;
         }    
         case "退款中":{
             $orderStatus = -2;
             break;
         }    
         //以下处理京卫订单状态转换

         case "已确认,已付款,未发货":{
             $orderStatus = 2;
             break;
         }    
         case "已确认,已付款,已发货":{
             $orderStatus = 3;
             break;
         }    
         case "已确认,已付款,收货确认":{
             $orderStatus = 4;
             break;
         }    
         case "已确认,未付款,未发货":{
             $orderStatus = 1;
             break;
         }    
         case "未确认,未付款,未发货":{
             $orderStatus = 0;
             break;
         }    
         case "退款,已付款,未发货":{
             $orderStatus = -2;
             break;
         }    
         case "退款,已付款,已发货":{
             $orderStatus = -2;
             break;
         }    
         case "退款,已付款,收货确认":{
             $orderStatus = -2;
             break;
         }    
         case "已取消,未付款,未发货":{
             $orderStatus = 5;
             break;
         }    
         case "无效,未付款,未发货":{
             $orderStatus = 5;
             break;
         }    
         default:
             $orderStatus = 0;
       }
       return $orderStatus ;
    }

    //get express id by name or option_name
    function getExpressId($str){
        if(empty($str))
            return 0;
        $express = S('express');
        foreach ($express as $key => $value) {
            if($value['name'] == $str || $value['option_name']  == $str)
                return $key;
        }
        return 0;
    }

    //返回订单的商品总数量
    function getSumNumber($sale_no){
         $s = M('Sale_detail')->where('sale_no ="'.$sale_no.'"')->sum('number');
         return empty($s) ? 0 : $s;
    }

    //返回订单的商品货款总额
    function getGoodsTotalMoney($sale_no,$type='sale'){
        if ($type == 'sale' )
         $s = M('Sale_detail')->where('sale_no ="'.$sale_no.'"')->sum('total');
        else //wholesale 
         $s = M('Wholesale_detail')->where('wholesale_no ="'.$sale_no.'"')->sum('total');
         return empty($s) ? 0 : $s;
    }

    function fixMobile($mobile_str){
        preg_match("/(\d+)/",  $mobile_str,$m);
        return empty($m[0]) ? '' : $m[0] ;
    }

    function printGoodsOption($goods_id){
        $options = getGoodsDetail( $goods_id );
        $option_str = "";
        foreach ($options['option'] as $op) {
            $option_str .= $op['option'] .':'. $op['name'].'<br>';
        }
        return $option_str;
    }

    //print contact lens option:level,color
    function printLensOption($goods_id){
        $options = getGoodsDetail( $goods_id );
        $option_str = "";
        foreach ($options['option'] as $op) {
            if($op['option'] =="光度" || $op['option'] =="颜色")
                $option_str .=  $op['name'].'<br>';
        }
        return $option_str;
    }

            // $dataArray = the data to write out
          // $delimeter = the field separator
        function build_csv_line($dataArray,$delimiter=',',$enclosure= '"' )
        {
           // Build the string
          $string = "";
          
          // No leading delimiter
          $writeDelimiter = FALSE;
          $writeDelimiter = FALSE;
          foreach($dataArray as $dataElement)
           {
            // Replaces a double quote with two double quotes
            $dataElement=str_replace("\"", "\"\"", $dataElement);
            
            // Adds a delimiter before each field (except the first)
            if($writeDelimiter) $string .= $delimiter;
            
            // Encloses each field with $enclosure and adds it to the string
            $string .= $enclosure . $dataElement . $enclosure;
            
            // Delimiters are used every time except the first.
            $writeDelimiter = TRUE;
           } // end foreach($dataArray as $dataElement)
          
          // Append new line
          $string .= "\n";
          return $string;
        }

    function export_csv($filename,$data) { 
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $data; 
    }

    

    //根据订单号输出合并订单号样式或单个订单号
    function getMergeNo($sale_no){
        if(strpos($sale_no, ',') === false )
            return $sale_no;
        $new_no = explode(',', $sale_no);
        return $new_no[0].'(合并'.count($new_no).')';
    }

    //提交 到药房网平台置该订单为已发货
    /**
    **@oid 订单号
    **@logicompany 快递公司名称
    **@logino 运单号
    **@logicompany_id 快递公司编号
    **@order_source_id 订单来源
    **@moible 用户 手机 号,方便药房网发送发货短信通知
    **/
    function jw_shipping($oid,$logicompany,$logino,$logicompany_id = 0,$order_source_id=0,$mobile=0)
    {
        ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
        set_time_limit(3000);// 时间约一小时

        // create a new cURL resource
      $ch = curl_init();
       $logicompany = empty($logicompany)?"韵达快运" :$logicompany ;
       if(empty($logino) || empty($oid) )
            return;
        //logino is not right,return;
        if(!is_logino($logino,$logicompany_id))
            return;
        if(strlen($oid)>7 ) //只传递京卫的单号，特征等于7
           return;

      $cookie_file = jw_login();

      $order_source = 0; //对应药房网自身订单来源
      switch($order_source_id){
         case 1:
            $order_source = 0; //药房网
            break;
         case 2:
            $order_source = 5; //京东
            break;
         case 3:
            $order_source = 0; //淘宝 原淘宝参数是1,现为了能正常使用,改为0
            break;
         case 9:
            $order_source = 2; //当当  
            break;
         default:
            $order_source = 0;
      }

      $post_data = array();
      $post_data['express'] = $logicompany;
      $post_data['invoice_no'] = $logino;
      $post_data['about_shipping_time'] = toDate(time()); 
      $post_data['order_source'] = $order_source;
      $post_data['tel'] = $mobile;
      //$url='http://mgr.yaofang.cn/order/update_express/'.$oid;
      $url='http://dealer.yaofang.cn/order/update_express/'.$oid;
      $o="";
      foreach ($post_data as $k=>$v)
      {
          $o.= "$k=".urlencode($v)."&";
      }
      $post_data=substr($o,0,-1);
      $ch = curl_init();
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_REFERER => $url, //伪装url
                  CURLOPT_HEADER => 0,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_POST => 1,
                  CURLOPT_POSTFIELDS => $post_data,
                  CURLOPT_RETURNTRANSFER => 1,
                  CURLOPT_FOLLOWLOCATION => 1,
                  CURLOPT_COOKIEFILE => $cookie_file,
                  CURLOPT_TIMEOUT => 300
              );
 
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        //如果发货成功，则置为已经平台发货
        if($result == "订单配送状态完成！")
            M('Sale')->where('sale_no = "'.$oid.'"')->setField('is_shipping_mall',1);
        curl_close($ch);
    }

    //默认不填快递公司情况下，如果运单号小于12或不为数字，则提示错误；其他情况根据快递公司规则处理 则返回false;正确则返回true
   function is_logino($logino,$logicompany_id = 0){
    //如果不为空时，则进行判断
    if(!empty($logino)){
        if( $logicompany_id == 20 && strlen($logino) != 12 && strlen($logino) != 10 )  //圆通 12
          return false;
        else if( $logicompany_id == 17 && strlen($logino) != 12 )  //中通 12
          return false;
        else if( $logicompany_id == 18 && strlen($logino) != 12 )  //汇通快运 12
          return false;
        else if( $logicompany_id == 21 && strlen($logino) != 13 )  //韵达13
          return false;
        else if( $logicompany_id == 27 && strlen($logino) != 13 )  //邮政国内小包 13
          return false;
        else if(!is_numeric($logino))
           return false;
        else
           return true;
    }
    return false;
     

    }

    //jw yaofang.cn login
     function jw_login(){
       $cookie_file = "";  //检查是否已经存在，若存在，则不用再登录
        if(file_exists($_SERVER[DOCUMENT_ROOT].__ROOT__.'/Admin/Runtime/Temp/jw_cookie.tmp')){
           $cookie_file = $_SERVER[DOCUMENT_ROOT].__ROOT__.'/Admin/Runtime/Temp/jw_cookie.tmp';
            if(filesize( $cookie_file ) > 0 &&  ( filemtime($cookie_file )+1440 > time() ) ){
                //必须在会话有效期内
                return $cookie_file;
            }else{
                unlink($cookie_file); //删除过期cookie文件
                fopen($_SERVER[DOCUMENT_ROOT].__ROOT__.'/Admin/Runtime/Temp/jw_cookie.tmp', "w");
                $cookie_file = $_SERVER[DOCUMENT_ROOT].__ROOT__.'/Admin/Runtime/Temp/jw_cookie.tmp';
            }

        }
        else{ //创建文件 必须使用绝对路径
            fopen($_SERVER[DOCUMENT_ROOT].__ROOT__.'/Admin/Runtime/Temp/jw_cookie.tmp', "w");
            $cookie_file = $_SERVER[DOCUMENT_ROOT].__ROOT__.'/Admin/Runtime/Temp/jw_cookie.tmp';
        }

      $post_data = array();
      /*new yaofang sys
      $post_data['username'] = "大眼窝";
      $post_data['password'] = "jw321@dyw";
      $url='http://mgr.yaofang.cn/login/do_login';
      */
      $post_data['dealer_name'] = "大眼窝";
      $post_data['dealer_psw'] = "jw321@dyw";
      $post_data['autoLogin'] = 'Auto409'; //突破验证码
      $url='http://dealer.yaofang.cn/dealer/login';
      $o="";
      foreach ($post_data as $k=>$v)
      {
          $o.= "$k=".urlencode($v)."&";
      }
      $post_data=substr($o,0,-1);
      
      $ch = curl_init();
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_HEADER => 0,
                  //CURLOPT_HTTPHEADER => $header,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_POST => 1,
                  CURLOPT_POSTFIELDS => $post_data,
                  CURLOPT_RETURNTRANSFER => 1, //1 return no grab content
                  CURLOPT_FOLLOWLOCATION => 1,
                  CURLOPT_COOKIEJAR =>  $cookie_file, //必须使用jar
                  //CURLOPT_COOKIEFILE => $cookie_file,
                  CURLOPT_TIMEOUT => 300
              );
 
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        curl_close($ch);
        return $cookie_file;
    }

    function getFinishStatus($finish){
      return $finish == 1 ? "是":"否";
    }

    //判断采购单是否完全入库结束，若是，则返回1
    function is_all_finish($buy_id='')
    {
        if(empty($buy_id))
            return 0;
        $buy_details = M('Buy_detail')->where('buy_id ='.$buy_id)->field('finish')->findAll();
        foreach ($buy_details as $value) {
            if($value['finish'] == 0 ){
                return 0;
                break;
            }
                
        }
        return 1;

    }

    //是否全部是虚拟物品.若是，则返回1
    function is_all_virtual($order_id='')
    {
        if(empty($order_id))
            return 0;
        //如果是合并订单的 ，则ID会以,分隔开
        $condition = array ('sale_id' => array ('in', explode ( ',', $order_id ) ) );
        $sale_details = M('Sale_detail')->where($condition)->field('product_id')->findAll();
        foreach ($sale_details as $value) {
            if(getModelName($value['product_id'],'Product','is_virtual') == 0 ){
                return 0;
                break;
            }
                
        }
        return 1;

    }

//根据淘宝地址特有的三个空格来获取对应的省，市，区或县
   function get_tb_address($add="")
  {
    $return_address = array();
    if(empty($add))
        return null;
    $first_blank_address = strpos($add, " ");
    $province = substr($add, 0,$first_blank_address);

    $left_add = substr($add, $first_blank_address+1); //去掉开头的空白
    $second_blank_address = strpos($left_add," ");
    $city = substr($left_add, 0,$second_blank_address);

    $last_add = substr($left_add, $second_blank_address+1); //去掉开头的空白
    $third_blank_address = strpos($last_add," ");
    $county = substr($last_add, 0,$third_blank_address);
    
    $return_address = array(
      'province' => $province,
      'city' => $city,
      'county' => $county
      );

    if(count($return_address) > 1 )
        return $return_address;
    else
        return null;
  }


    function word_wrap($str){
      echo "<div style='width:120px;word-wrap:break-word;'>".$str."</div>";
    }
    //是否是隐形眼镜类产品,如果是,则返回true,否则返回false
    function is_lens_order($keywords = ""){
        if (empty($keywords))
            return false;
        
        if(strpos($keywords,'隐形眼镜') !== false || strpos($keywords,'隐形眼眼镜') !== false  || strpos($keywords,'眼镜') !== false ||strpos($keywords,'美瞳') !== false ||  strpos($keywords,'优能') !== false || strpos($keywords,'护理液') !== false|| strpos($keywords,'润眼液') !== false || strpos($keywords,'洗眼液') !== false || strpos($keywords,'清洗液') !== false)
           return true;
        return false;
    }
/* 
* 自动识别文字编码并转换 
* 来源URL : http://www.xuehuwang.com/ 
* 作者: 雪狐博客 
*/
function detect_encoding($string,$encoding = 'gbk'){ 
    $is_utf8 = (@iconv('utf-8', 'utf-8//IGNORE', $string) === $string) ? true : false; 
    $is_gbk = (@iconv('gbk', 'gbk//IGNORE', $string) === $string) ? true : false; 
    if($is_utf8 && strtolower($encoding) == 'utf-8'){ 
          return $string; 
    }elseif($is_utf8){ 
       return iconv('utf-8',$encoding,$string); 
    }elseif($is_gbk && strtolower($encoding) == 'gbk'){ 
       return $string;  
    }elseif($is_gbk){ 
       return iconv('gbk',$encoding,$string);   
    }
    else{ 
        return mb_convert_encoding($string, $encoding, 'gbk,gb2312,big5');   
    } 
}

//通过详细地址信息返回相应的省，市。区县
//$address = '湖北省武汉市江夏区洋湖大道湖北经济学院汀兰苑小高层';
function getGEO($address=""){
    if(empty($address))
        return;
    preg_match_all('/(.+?(?<=省|市|区|县|镇))/', $address, $match);
    $re = $match[0];
    return $re;
}

?>
